package cn.com.connext.scrm.web.rest;

import cn.com.connext.scrm.service.CardCouponService;
import cn.com.connext.scrm.service.dto.CardCouponDto;
import cn.com.connext.scrm.service.dto.JsonResult;
import cn.com.connext.scrm.web.rest.vm.CardCouponAddressVM;
import cn.com.connext.scrm.web.rest.vm.CardCouponDetailVM;
import cn.com.connext.scrm.web.rest.vm.QueryCardCouponVM;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;

/**
 * 卡券
 */
@RestController
@RequestMapping("/api/cardcoupon")
public class CardCouponResource {

    private static final Logger log = LoggerFactory.getLogger(CardCouponResource.class);

    @Autowired
    private CardCouponService cardCouponService;

    @ApiOperation(value = "查询卡券列表")
    @PostMapping("/list")
    public JsonResult list(@RequestBody QueryCardCouponVM vm) {
        JsonResult result = new JsonResult();
        if (!StringUtils.hasText(vm.getUnionId())) {
            result.setState(JsonResult.ERROR);
            result.setData(Collections.EMPTY_LIST);
            result.setMessage("用户ID不能为空！");
            return result;
        }

        List<CardCouponDto> list = cardCouponService.list(vm);
        result.setData(list);
        result.setState(JsonResult.SUCCESS);
        return result;
    }

    @ApiOperation(value = "查询卡券详情")
    @PostMapping("/detail")
    public JsonResult detail(@RequestBody CardCouponDetailVM vm) {
        JsonResult result = new JsonResult();
        try {
            CardCouponDto detail = cardCouponService.detail(vm);
            result.setData(detail);
            result.setState(JsonResult.SUCCESS);
        } catch (IllegalArgumentException e) {
            result.setState(JsonResult.ERROR);
            result.setMessage(e.getMessage());
        } catch (Exception e) {
            log.error("查询卡券详情出现异常", e);
            throw e;
        }
        return result;
    }

    @ApiOperation(value = "新增、更新卡券地址")
    @PostMapping("/address")
    public JsonResult address(@RequestBody CardCouponAddressVM vm) {
        JsonResult result = new JsonResult();
        try {
            cardCouponService.address(vm);
            result.setState(JsonResult.SUCCESS);
            result.setMessage("保存成功");
        } catch (IllegalArgumentException e) {
            result.setState(JsonResult.ERROR);
            result.setMessage(e.getMessage());
        }
        return result;
    }
}
